package cn.wolfcode.education.realm;

import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.mapper.EmployeeMapper;
import cn.wolfcode.education.mapper.PermissionMapper;
import cn.wolfcode.education.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
//自定义realm
public class UserRealm extends AuthorizingRealm {
    public String getName() {
        return "UserRealm";
    }
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    public void setPermissionMapper(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    public void setEmployeeMapper(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }
    //获取授权信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取到用户名
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        //根据用户名获取该用户的角色列表
        List<String> roleSns = null;
        //根据用户名获取该用户的权限列表
        List<String> permissionResources = null;
        if (employee.isAdmin()) {
            //如果是管理员,拥有所有的角色,和权限
            roleSns = roleMapper.listSnsAll();
            permissionResources = Arrays.asList("*:*");
        } else {
            roleSns = roleMapper.listSnsByEmployeeId(employee.getId());
            permissionResources = permissionMapper.listResourcesByEmployeeId(employee.getId());
        }

        //角色和权限封装
        SimpleAuthorizationInfo inf = new SimpleAuthorizationInfo();
        inf.addRoles(roleSns);
        inf.addStringPermissions(permissionResources);
        return inf;
    }
    //获取认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取登陆的用户名
        String username = (String) token.getPrincipal();

        //从数据库查询该用户的信息
        Employee employee = employeeMapper.getByUsername(username);
        if (employee == null) {
                return null;
        }

        //封装成  AuthenticationInfo 对象返回 :
        AuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(),
                ByteSource.Util.bytes(employee.getUsername()), getName());
        return info;
    }
}
